/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 关键词回复
 *  */
import React, { useState, useCallback, useEffect, useMemo } from "react";
import { useSelector, useDispatch } from "dva";
import { Form, Modal, Input, Row, Col, Button, Popconfirm, Table, message } from "antd";
import AddInfo from "./components/AddInfo";

const FormItem = Form.Item;

const selectPlatform = ({ platform: { platformList: { weixin = {} } = {} } = {} }) =>
  weixin.platform;

const KeywordReply = props => {
  const { form } = props;
  const { getFieldDecorator, validateFields } = form;

  const dispatch = useDispatch();
  const platform = useSelector(selectPlatform);

  const [tableList, setTableList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [record, setRecord] = useState({});

  const getTableList = useCallback(
    () => {
      if (!platform) {
        message.warn("暂无绑定的微信公众号平台，请先到”微信管理-设置”中新增关联！");
        return;
      }
      dispatch({
        type: "massPush/getKeyWordReplyList",
        payload: {
          platform,
        },
      }).then(list => {
        setTableList(list);
      });
    },
    [dispatch, platform]
  );

  const onDelete = useCallback(
    (key_word_id, platform) => {
      dispatch({
        type: "massPush/delKeyWordReply",
        payload: {
          key_word_id,
          platform,
        },
      }).then(() => {
        getTableList(platform);
      });
    },
    [dispatch, getTableList]
  );

  const onSubmit = useCallback(
    (content, error, record) => {
      validateFields((err, val) => {
        if (err || error) return;
        const add = () => {
          const { key_word_id } = record;
          const type = key_word_id ? "massPush/editKeyWordReply" : "massPush/addKeyWordReply";
          const payload = {
            platform,
            key_word: val.key_word,
            content,
          };
          if (key_word_id) {
            payload.key_word_id = key_word_id;
          }

          dispatch({
            type,
            payload,
          }).then(() => {
            setVisible(false);
            getTableList();
          });
        };
        Modal.confirm({
          title: "温馨提示",
          okText: "确定",
          cancelText: "取消",
          onOk: add,
          content: "确定后，用户输入对应关键词，会回复此消息",
        });
      });
    },
    [validateFields, dispatch, platform, getTableList]
  );

  const onAdd = useCallback(() => {
    setVisible(true);
    setRecord({});
  }, []);

  const onEdit = useCallback(record => {
    setRecord(record);
    setVisible(true);
  }, []);

  const onTest = useCallback(
    content => {
      validateFields(err => {
        if (err) return;

        Modal.confirm({
          title: "温馨提示",
          okText: "确定测试",
          cancelText: "取消",
          onOk: () => {
            dispatch({
              type: "massPush/testKeyWordReply",
              payload: {
                platform,
                content,
              },
            });
          },
          content: (
            <Row>
              <Col>
                您点击【确定测试】，关注定制公众号并绑定此管理平台登录手机号的用户，将接收到此消息，用于检测是否正常推送
              </Col>
              <Col>注：测试前请确保已关注定制公众号，并在公众号内已绑定管理平台登录手机号</Col>
            </Row>
          ),
        });
      });
    },
    [platform, dispatch, validateFields]
  );

  const onCancel = useCallback(() => {
    setVisible(false);
  }, []);

  const columns = useMemo(
    () => [
      {
        dataIndex: "key_word",
        key: "key_word_id",
        width: "20%",
        title: "关键词",
      },
      {
        dataIndex: "content",
        key: "content",
        title: "关键词内容",
      },
      {
        title: "操作",
        width: "20%",
        align: "center",
        render: record => {
          const { key_word_id } = record;
          return (
            <Row type="flex" justify="space-around">
              <Col>
                <a onClick={() => onEdit(record)}>编辑</a>
              </Col>
              <Col>
                <Popconfirm
                  title="确认删除该条数据？"
                  onConfirm={() => onDelete(key_word_id, platform)}
                >
                  <a>删除</a>
                </Popconfirm>
              </Col>
            </Row>
          );
        },
      },
    ],
    [onDelete, platform, onEdit]
  );

  useEffect(
    () => {
      getTableList();
    },
    [getTableList]
  );

  return (
    <div>
      <Row type="flex" justify="space-between">
        <Col span={8} push={1} />
        <Col span={8} pull={1}>
          {/* <Input.TextArea rows="10" /> */}
        </Col>
      </Row>
      <Row style={{ marginTop: 10, marginBottom: 10 }} type="flex" justify="space-between">
        <Col style={{ fontWeight: "bolder", fontSize: "16px" }}>
          注：1、设置关键词及其对应回复内容，在公众号对话框内输入关键词，会自动回复相应内容。2，回复内容可展示文字或跳转H5/小程序链接
        </Col>
        <Col>
          <Button onClick={onAdd} icon="plus" type="primary">
            添加关键词
          </Button>
        </Col>
      </Row>
      <Modal
        center
        destroyOnClose
        visible={visible}
        onCancel={() => setVisible(false)}
        title="关键词设置"
        footer={null}
      >
        <Form>
          <FormItem label="设置关键词">
            {getFieldDecorator("key_word", {
              initialValue: record.key_word,
              rules: [
                {
                  required: true,
                  message: "请输入关键词",
                },
              ],
            })(<Input placeholder="请输入关键词" />)}
          </FormItem>
        </Form>
        <AddInfo
          value={record.content || ""}
          onTest={onTest}
          onCancel={onCancel}
          onSubmit={(content, { err }) => onSubmit(content, err, record)}
          contentTitle="设置回复文本内容"
        />
      </Modal>
      <Table rowKey="key_word_id" columns={columns} dataSource={tableList} pagination={false} />
    </div>
  );
};

export default Form.create()(KeywordReply);
